import React from 'react'
import { getDetailApi } from '@/api/detail'
import {addCartApi,getCartListApi} from '@/api/cart'
import { Ellipsis, ImageViewer, Mask, Button, Space,Toast,Badge } from 'antd-mobile'
import { PlayOutline } from 'antd-mobile-icons'
// 获取路由参数
import { useParams,useHistory } from 'react-router-dom'
import { useEffect,useState,useCallback } from 'react'
import MyNavBar from '@/components/MyNavBar'
import MySwiper from '@/components/MySwiper'
import styled from 'styled-components'
import { useSelector } from 'react-redux'
import { useRef } from 'react'


// 播放按钮的样式
const MyBtn = styled.div`
    position:fixed;
    top:50%;
    left:50%;
    transform:translateX(-50%);
  `

// 根据路由参数proid, 获取详情页数据
export default function Detail(ref) {
  const ref1 = useRef()
  console.log('ref1',ref);
  const {userId} = useSelector(state => state)
// console.log( store );
  const [swiperList, setSwiperList] = useState([])
  const par = useParams()
  // console.log(par);//proid
  const [goodsObj, setGoodsObj] = useState({})
  // 处理价格函数
  const formatMoneyFn = (money) => {
    return <span style={{
      fontSize: '17px',
      color: 'red',
      marginLeft: '8px',
      fontWeight: 'bold'
    }}>${money}</span>
  }
  // 购物车数量初始值
  const [cartNum,setCartNum] = useState(0)

  // !使用useCallback处理函数 防止重复创建
  // 查看购物车列表接口
  const getCartListFn = useCallback(()=>{
    getCartListApi({
      userid:userId
    }).then(res=>{
      console.log('购物车列表',res);
      if(res.data.code=='200'){
        
        const sum = res.data.data.reduce((sum,item)=>{
          return sum+=item.num
        },0)
        // 修改徽标数量
        setCartNum(sum)
      }else{
        setCartNum(0)
      }
    })
  },[])

  // 预览图片数组
  useEffect(() => {
    getDetailApi(par).then(res => {
      // console.log(res);
      // setSwiperList(res.data.data.banners[0].split(','))
      // 改造数据
      let newSwiperList = res.data.data.banners[0].split(',').map((item, index) => {
        return {
          bannerid: index,
          img: item
        }
      })
      setSwiperList(newSwiperList)
      let obj = res.data.data
      obj.desc = res.data.data.desc.replace(/\n/g, '')
      setGoodsObj(obj)
    })
      // 初始化调用购物车列表接口
      getCartListFn()
  }, [])
  // 是否显示图片预览
  const [visible, setVisible] = useState(false)
  // 定义一个事件传给父组件 该事件控制visible是否显示

  const changeVisibelFn = (index) => {
    setVisible(true)
    ref1.current.swipeTo(index)
    console.log('ref1',ref1);

  }
  // 是否显示视频蒙层mask
  const [visibleVideo, setVisibleVideo] = useState(false)
  const his = useHistory()

  return (
    <div>
      {/* 导航条部分 */}
      <MyNavBar isShow={true}>详情</MyNavBar>
      {/* 轮播图部分 */}
      <MySwiper swiperList={swiperList} changeVisibelFn={changeVisibelFn} ></MySwiper>

      {/* 图片预览 */}
      <ImageViewer.Multi
        images={swiperList.map((item) => { return item.img })}
        visible={visible}
        ref={ref1}
        onClose={() => {
          setVisible(false)
        }}	
    
      />
      {/* 显示video */}
      <MyBtn>
        <Button onClick={() => setVisibleVideo(true)}><PlayOutline color='#e76813'/> 00:16:00</Button>
      </MyBtn>
      <Mask visible={visibleVideo} onMaskClick={() => setVisibleVideo(false)}>
        {
          visibleVideo ? <video
            autoPlay
            controls
            // preload=''
            src='https://jvod.300hu.com/vod/product/b1024a62-8c46-464c-8ec7-f57d26cceb38/42f70c8e8bbb442e986874ec556fc882.mp4'
            style={{
              position: 'absolute',
              top: '10%',
              left: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '100%',
              borderRadius: '16px'
            }}
          ></video> : <></>

        }
      </Mask>
      {/* 商品信息 */}
      <p> {formatMoneyFn(goodsObj.originprice)} </p>

      <div style={{
        fontSize: '18px',
        fontWeight: 'bold'
      }}><Ellipsis content={goodsObj.desc} rows={2} direction='end'></Ellipsis></div>
      {/* 底部的Tabbar 加入购物车 立即购买 */}
      <Space style={{
        position: 'fixed',
        bottom: 0,
        left: 0
      }}>
        {/* 徽标 -- Badge */}
         <Badge content={cartNum}>
        <p style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center'
        }} 
        onClick={()=>{
          if(localStorage.getItem('token')){
            his.push('/cart')
          }
        }}
        >
          <span className='iconfont icon-gouwuche'></span>
          <span style={{
            marginLeft:'5px'
          }}>购物车</span>
        </p>
        </Badge>
  
        <Button color='danger' style={{
          borderRadius:'20px',
          width:'130%',
          marginBottom:'5px'
        }}
          onClick={()=>{
            if(localStorage.getItem('token')){
              // 说明已经登录 -- 实现加入购物车的逻辑 调用加入购物车接口
              addCartApi({
                userid:userId,  //从redux中获取 通过useSelector hook
                proid:goodsObj.proid,
                num:1
              }).then(res=>{
                // console.log('res666',res)
                if(res.data.code == 200 ){
                  Toast.show({
                    icon:'success',
                    content:'成功加入购物车'
                  })
                  // 重新修改徽标 调用购物车接口
                  getCartListFn()
                }else{
                  Toast.show({
                    icon:'fail',
                    content:res.data.message
                  })
                }
            })
            }else{
              Toast.show({
                content:'请先登录',
                afterClose(){
                  his.push('/login')
                }
              })
            }
          }}
        >加入购物车</Button>
        <Button color='primary' style={{
          borderRadius:'20px',
          width:'130%',
          marginLeft:'30px'
        }}>立即购买</Button>


      </Space>

    </div>
  )
}
